import axios from "axios";
import { generateSign } from "../utils/signUtil";
import { useUserStore } from "../store/userStore";

// 创建 axios 实例
const service = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const configStore = useUserStore();
    const appId = configStore.appId;
    const appSecret = configStore.appSecret;
    const timestamp = new Date().getTime();
    const baseUrl = config.url || "";
    const params = config.params || {};
    const sign = generateSign(appId, appSecret, baseUrl, params, timestamp);
    config.headers["Authorization"] = sign;
    config.params = {
      ...config.params,
      appId,
      timestamp,
      sign,
    };
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    return res;
  },
  (error) => {
    // 对响应错误做些什么
    console.log("请求错误:", error.message);
    return Promise.reject(error);
  }
);

export default service;
